package com.kindergarten.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kindergarten.mapper.RoleMapper;
import com.kindergarten.mapper.UserRoleMapper;
import com.kindergarten.pojo.Role;
import com.kindergarten.pojo.User;
import com.kindergarten.mapper.UserMapper;
import com.kindergarten.pojo.UserRole;
import com.kindergarten.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bruce
 * @since 2022-10-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Resource
    UserMapper userMapper;

    @Resource
    UserRoleMapper userRoleMapper;

    @Resource
    RoleMapper roleMapper;

    /**
     * 查询自己的数据库
     * @param userId
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        //根据账号查询对象
        User userPojo = userMapper.selectById(userId);
        if (userPojo != null) {
            //角色集合
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            // 查询当前登录用户具备的角色
            UserRole userRole = userRoleMapper.selectOne(new QueryWrapper<UserRole>().eq("user_id", userId));
            if(userRole!=null){
                Role role = roleMapper.selectById(userRole.getRoleId());
                System.out.println("当前用户登录的角色是："+role.getName());
                authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
            }
            //账号存在
            UserDetails user =
                    new org.springframework.security.core.userdetails.User(userPojo.getUserId(), userPojo.getUserPassword(),
                            userPojo.getDel() == 0,  //账号启用的
                            true,
                            true,
                            true,
                            authorities);
            return user;
        } else {
            return null;
        }
    }
}
